package org.smart4j.framework.helper;

import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.smart4j.framework.annotation.Inject;
import org.smart4j.framework.util.ReflectionUtil;

import java.lang.reflect.Field;
import java.util.Map;

/*
* 依赖注入助手类
* */
public class IocHelper {
    static {
        Map<Class<?>, Object> beanMap = BeanHelper.getBeanMap();
        if (!MapUtils.isEmpty(beanMap)){
            //遍历beanMap
            for (Map.Entry<Class<?>, Object> beanEntity : beanMap.entrySet()){
                Class<?> beanClass = beanEntity.getKey();
                Object beanInstance = beanEntity.getValue();
                //获取bean类定义的所有成员变量
                Field[] beanFields = beanClass.getDeclaredFields();
                if (!ArrayUtils.isEmpty(beanFields)){
                    //遍历beanFields
                    for (Field beanField : beanFields){
                        //判断当前beanField是否带有Inject注解
                        if (beanField.isAnnotationPresent(Inject.class)){
                            //在beanMap中获取beanField对应的实例
                            Class<?> beanFieldClass = beanField.getType();
                            Object beanFieldInstance = beanMap.get(beanFieldClass);
                            if (beanFieldInstance != null){
                                ReflectionUtil.setField(beanInstance, beanField, beanFieldInstance);
                            }

                        }
                    }
                }
            }
        }

    }

}
